<?php
class AdminController extends AppController
{
    public $name = "Admin";
    public $layout = "admin";
    public $components = array('obAuth', 'PasswordGenerator', 'Image', 'MyEmail', 'Image');
    public $uses = array('User', 'Message', 'Business', 'BusinessDetail', 'State', 'Plan', 'Account', 'Offer', 'Field', 'CustomField', 'Network', 'OfferCategory', 'Country');

    public $paginate = array('Business' =>
                              array('fields' =>
                                     array("`Business`.`id`", "`Business`.`name`", "`Business`.`category`",
                                           "`Business`.`active`", "`Plan`.`name`", "`User`.`lastname`",
                                           "`User`.`firstname`", "`User`.`date_registered`"),
                                    'limit' => 20
                                    ),
                             'User' =>
                              array('fields' =>
                                     array("`User`.`id`", "`User`.`lastname`", "`User`.`firstname`",
                                           "`User`.`email`", "``User`.`date_registered`"),
                                    'limit' => 20
                                    ),
                             'Offer' =>
                              array('limit' => 15,
                                    'conditions' => array('active' => 1),
                                    'order' => array('date_added' => 'desc')
                                    ),
                             'Network' =>
                              array('limit' => 20,
                                    'conditions' => array('active' => 1)
                                    ),
                             'OfferCategory' =>
                              array('limit' => 20,
                                    'conditions' => array('active' => 1),
                                    'order' => array('sub_category' => 'ASC')
                                    )
                             );


    public function home()
    {
        # The parameter of lock() is the access level a
        # transporter would have.
        $this->obAuth->lock(array($this->obAuth->getGroupId()));
        self::set('group_id', $this->obAuth->getGroupId());

        // generate conditions based on user's
        // level and access
        switch ($this->obAuth->getGroupId()) {
            case 2:
                $conditions = array('user_id' => $this->obAuth->getUserId(), 'msg_type' => 'MESSAGE');
                break;

            default:
                $conditions = array('projectId' => $this->Session->read('projectId'), 'msg_type' => 'CONTACT');
                break;
        }

        $fields = array('name', 'email', 'body', 'date_created');
        $result = $this->Message->findAll($conditions, $fields, "`Message`.`date_created` DESC", 20);
        if ($result) {
            $this->set('messages', $result);
            $this->set('msg_count', $this->Message->findCount($conditions));
        } else {
            $this->set('messages', null);
            $this->set('msg_count', 0);
        }

        # process form request
        switch ($this->data['window']['flag']) {
            case "uprofile":
                $this->redirect('/admin/uprofile');
            break;

            case "bprofile":
                $this->redirect('/admin/bprofile');
            break;
        }

        self::set(array('logo' => $this->Session->read('logo'),
                        'wbtitle' => $this->Session->read('wbtitle')));
    }

    public function index()
    {
        $alert = "";
        if (isset($this->data['User'])) {
            if ($this->obAuth->login($this->data['User'])) {
                $hash = $this->Session->read();
                $id = $hash['mYpERsOnALhaSHkeY']['User']['id'];
                self::redirect('/admin/home/');
            } else {
                $alert = 'Invalid username/password';
            }
        }

        self::set(array('logo' => $this->Session->read('logo'),
                        'wbtitle' => $this->Session->read('wbtitle'),
                        'alert' => $alert
                        )
                  );
    }

    public function logout()
    {
        $this->obAuth->logout();
        self::redirect("/admin/index/");
    }

    public function addcompany()
    {
        # The parameter of lock() is the access level a
        # transporter would have.
        $this->obAuth->lock(array(1));

        $plans = $this->Plan->myGenerateList(array('projectID' => $this->Session->read('projectId')), 'Plan.name ASC', null,'{n}.Plan.name', '{n}.Plan.name', ' ');
        $state = $this->State->myGenerateList(null, 'State.name ASC', null,'{n}.State.name', '{n}.State.name', ' ');

        if (isset($this->data['plan'])) {
            self::set('plan', $this->data['plan']);
        } else {
            self::set('plan', null);
        }
        self::set('plans', $plans);
        self::set('state', $state);

        if ($this->data['user']['lastname'] && $this->data['user']['firstname'] &&
            $this->data['user']['email'] &&
            $this->data['business']['name'] && $this->data['business']['keyword'] &&
            $this->data['business']['city'] && $this->data['business']['zip_code'] &&
            $this->data['business']['contact_no']) {

            # generate random passwords
            if ($this->data['user']['random'] == 1) {
                $random = $this->PasswordGenerator->generate();
            } else {
                $random = $this->data['user']['password'];
            }

            $user = array('lastname' => $this->data['user']['lastname'],
                          'firstname' => $this->data['user']['firstname'],
                          'email' => $this->data['user']['email'],
                          'password' => sha1($random),
                          'password_confirmation' => sha1($random),
                          'date_registered' => date('Y-m-d H:i:s'),
                          'projectId' => $this->Session->read('projectId'),
                          'active' => 1,
                          'group_id' => 2);

            $validate_email = $this->User->find(array('email' => $this->data['user']['email']));
            if (!$validate_email) {
                $cid = $this->User->_save(0, $user);
            } else {
                $cid = $validate_email['User']['id'];
            }

            if ($this->obAuth->getPlanId() == 3) {
                $pos = strpos($this->data['business']['website'], "http://");
                if ($pos === false) {
                    $this->data['business']['website'] = "http://" . $this->data['business']['website'];
                }
            }

            App::import('Sanitize');
            $sanitize = new Sanitize();

            switch ($this->data['plan']) {
                case "Premium Listing":
                    // upload the file
                    $image_path = $this->Image->upload_image_and_thumbnail($this->data['register'],"name1",573,80,"logo",true);
                    $data = array('name' => $sanitize->escape($this->data['business']['name']),
                                  'keyword' => $sanitize->escape($this->data['business']['keyword']),
                                  'description' => $sanitize->escape($this->data['business']['description']),
                                  'street' => $sanitize->escape($this->data['business']['street']),
                                  'city' => $sanitize->escape($this->data['business']['city']),
                                  'state' => $sanitize->escape($this->data['state']),
                                  'zip_code' => $sanitize->escape($this->data['business']['zip_code']),
                                  'contact_no' => $sanitize->escape($this->data['business']['contact_no']),
                                  'contact_person' => $sanitize->escape($this->data['business']['contact_person']),
                                  'website' => $sanitize->escape($this->data['business']['website']),
                                  'logo' => $image_path,
                                  'projectId' => $this->Session->read('projectId'),
                                  'active' => 1,
                                  'user_id' => $cid
                                  );
                     break;

                 case "Enhanced Listing":
                     $data = array('user_id' => $cid,
                                   'name' => $sanitize->escape($this->data['business']['name']),
                                   'keyword' => $sanitize->escape($this->data['business']['keyword']),
                                   'description' => $sanitize->escape($this->data['business']['description']),
                                   'street' => $sanitize->escape($this->data['business']['street']),
                                   'city' => $sanitize->escape($this->data['business']['city']),
                                   'state' => $sanitize->escape($this->data['state']),
                                   'zip_code' => $sanitize->escape($this->data['business']['zip_code']),
                                   'contact_no' => $sanitize->escape($this->data['business']['contact_no']),
                                   'contact_person' => $sanitize->escape($this->data['business']['contact_person']),
                                   'website' => $sanitize->escape($this->data['business']['website']),
                                   'projectId' => $this->Session->read('projectId'),
                                   'active' => 1
                                   );
                     break;

                 case "Basic Listing":
                     $data = array('user_id' => $cid,
                                  'name' => $sanitize->escape($this->data['business']['name']),
                                  'keyword' => $sanitize->escape($this->data['business']['keyword']),
                                  'street' => $sanitize->escape($this->data['business']['street']),
                                  'city' => $sanitize->escape($this->data['business']['city']),
                                  'state' => $sanitize->escape($this->data['state']),
                                  'zip_code' => $sanitize->escape($this->data['business']['zip_code']),
                                  'contact_no' => $sanitize->escape($this->data['business']['contact_no']),
                                  'contact_person' => $sanitize->escape($this->data['business']['contact_person']),
                                  'projectId' => $this->Session->read('projectId'),
                                  'active' => 1
                                  );
                    break;
                default:
                    $data = null;
                    break;
            }

            $businessID = $this->Business->_save(0, $data);
            if (!$businessID) {
                self::set('alert', 'Error in saving account');
            } else {
                // get plan id
                $plan_id = $this->Plan->get_plan_id($this->data['plan'], $this->Session->read('projectId'));

                $account = array('user_id' => $cid,
                                 'plan_id' => $plan_id,
                                 'projectId' => $this->Session->read('projectId'),
                                 'active' => 1
                                 );

                $accountID = $this->Account->_save(0, $account);
                $this->Business->query("UPDATE `businesses` SET `plan_id`=".$plan_id." WHERE `id`=".$businessID);
                $plan = $this->Plan->findAll('`Plan`.`id`='.$plan_id);
                $redirect = "http://".$_SERVER['HTTP_HOST']."/ldsyellow/index.php/admin/login/";


                # send email to user specifying his/her admin console credentials.
                # send registration thank you email
                $data = array('lastname' => $sanitize->escape($this->data['user']['lastname']),
                              'firstname' => $sanitize->escape($this->data['user']['firstname']),
                              'wbtitle' => $this->Session->read('wbtitle'),
                              'email' => $this->data['user']['email'],
                              'password' => $random,
                              'wbbase' => $this->Session->read('wbbase')
                              );

                $this->MyEmail->to = $sanitize->escape($this->data['user']['email']);
                $this->MyEmail->subject = $this->Session->read('wbtitle') . " Registration";
                $this->MyEmail->from = $this->Session->read('reply_to');
                $this->MyEmail->template = "thankyou";
                $this->MyEmail->data = $data;

                if (!$this->MyEmail->send()) {
                    self::set('alert', 'Error in sending registration email');
                }

                self::set('alert', 'Account has been successfully created');
                self::redirect('/admin/home');
            }
        }

        self::set(array('logo' => $this->Session->read('logo'),
                        'wbtitle' => $this->Session->read('wbtitle')
                        )
                  );
    }

    public function view()
    {
        # The parameter of lock() is the access level a
        # transporter would have.
        $this->obAuth->lock(array(1));

        # generate pagination
        $_default = array("`Business`.`active`=1",
                          "`Business`.`deleted`=0",
                          "`Business`.`projectId`=".$this->Session->read('projectId'));
        $result = $this->paginate('Business', array($_default));
        if ($result) {
            self::set('business', $result);
            self::set('bus_count', $this->Business->findCount($_default));
        } else {
            self::set('business', null);
            self::set('bus_count', 0);
        }

        if (isset($this->data['window'])) {
            # process form request
            switch ($this->data['window']['flag']) {
                case "search":
                    if ($this->data['search']) {
                        if ($this->data['search']['company'] && !$this->data['search']['category']) {
                            $searchfields = array("`Business`.`name` LIKE" => "%{$this->data['search']['company']}%");
                        } else if (!$this->data['search']['company'] && $this->data['search']['category']) {
                            $searchfields = array("`Business`.`category` LIKE" => "%{$this->data['search']['category']}%");
                        } else if ($this->data['search']['company'] && $this->data['search']['category']) {
                            $searchfields = array("`Business`.`name` LIKE" => "%{$this->data['search']['company']}%",
                                                  "`Business`.`category` LIKE" => "%{$this->data['search']['category']}%"
                                                  );
                        }

                        $result = $this->paginate('Business', array($_default, $searchfields));
                        if ($result) {
                            self::set('business', $result);
                            self::set('bus_count', $this->Business->findCount(array($_default, $searchfields)));
                        } else {
                            self::set('business', null);
                            self::set('bus_count', 0);
                        }
                    }
                break;

                case "enable":
                    # enable business profile
                    if ($this->data['row']['id']) {
                        foreach ($this->data['row']['id'] as $id) {
                            $this->Business->_save($id, array('active' => 1));
                        }
                        self::redirect('/admin/view/');
                    }
                break;

                case "disable":
                    # deactivate business profile
                    if ($this->data['row']['id']) {
                        foreach ($this->data['row']['id'] as $id) {
                            $this->Business->_save($id, array('active' => 0));
                        }
                        self::redirect('/admin/view/');
                    }
                break;

                case "delete":
                    # delete business profile
                    if ($this->data['row']['id']) {
                        foreach ($this->data['row']['id'] as $id) {
                            $this->Business->_save($id, array('deleted' => 1));
                        }
                        self::redirect('/admin/view/');
                    }
                break;

            }
        }


        self::set(array('logo' => $this->Session->read('logo'),
                        'wbtitle' => $this->Session->read('wbtitle')
                        )
                  );
    }

    public function reset()
    {
        # The parameter of lock() is the access level a
        # transporter would have.
        $this->obAuth->lock(array(1));

        # generate pagination
        $_default = array("`User`.`active`=1",
                          "`User`.`projectId`=".$this->Session->read('projectId'));
        $result = $this->paginate('User', array($_default));
        if ($result) {
            self::set('users', $result);
            self::set('usr_count', $this->User->findCount($_default));
        } else {
            self::set('users', null);
            self::set('usr_count', 0);
        }

        # process form request
        switch ($this->data['window']['flag']) {
            case "search":
                if ($this->data['search']) {
                    $searchfields = array('OR' =>
                                           array("`User`.`lastname` LIKE" => "%{$this->data['search']['name']}%",
                                                 "`User`.`firstname` LIKE" => "%{$this->data['search']['name']}%"
                                                 )
                                          );

                    $result = $this->paginate('User', array($_default, $searchfields));
                    if ($result) {
                        self::set('users', $result);
                        self::set('usr_count', $this->User->findCount(array($_default, $searchfields)));
                    } else {
                        self::set('users', null);
                        self::set('usr_count', 0);
                    }
                }
            break;

            case "reset":
                # generate random passwords
                if ($this->data['row']['id']) {
                    foreach ($this->data['row']['id'] as $id) {
                        $random = $this->PasswordGenerator->generate();
                        $this->User->_save($id, array('password' => sha1($random),
                                                      'password_confirmation' => sha1($random)
                                                     )
                                          );
                        $info = $this->User->find('`User`.`id`='.$id);

                        # send email to user specifying his/her admin console credentials.
                        $data = array('lastname' => $info['User']['lastname'],
                                      'firstname' => $info['User']['firstname'],
                                      'wbtitle' => $this->Session->read('wbtitle'),
                                      'password' => $random
                                      );

                        $this->MyEmail->to = $info['User']['email'];
                        $this->MyEmail->subject = $this->Session->read('wbtitle') . " Reset Password";
                        $this->MyEmail->from = $this->Session->read('reply_to');
                        $this->MyEmail->template = "reset_password";
                        $this->MyEmail->data = $data;

                        if (!$this->MyEmail->send()) {
                            self::set('alert', 'Error in sending registration email');
                        }
                    }
                }
            break;
        }

        self::set(array('logo' => $this->Session->read('logo'),
                        'wbtitle' => $this->Session->read('wbtitle')
                        )
                  );
    }

    public function uprofile()
    {
        $userID = $this->obAuth->getUserId();
        $profile = $this->User->find(array('`User`.`id`' => $userID), array('lastname', 'firstname', 'email'));
        self::set('profile', $profile);
        self::set('uid', $userID);

        if (!empty($this->data['account'])) {
            $data = array('lastname' => $this->data['account']['lastname'],
                          'firstname' => $this->data['account']['firstname'],
                          'email' => $this->data['account']['email'],
                          'password' => sha1($this->data['account']['password']),
                          'password_confirmation' => sha1($this->data['account']['password_confirmation'])
                         );
            $result = $this->User->_save($this->obAuth->getUserId(), $data);
            if ($result) {
                self::set('alert',  'Password Successfully Changed');
            }
        }

        self::set(array('logo' => $this->Session->read('logo'),
                        'wbtitle' => $this->Session->read('wbtitle')
                        )
                  );
    }

    public function bprofile()
    {
        $userID = $this->obAuth->getUserId();
        if ($userID) {
            $bid = (isset($this->params['pass'][0])) ? $this->params['pass'][0] : $userID;

            $sql = "SELECT `businesses`.`id`, `businesses`.`name`, `businesses`.`active`, `plans`.`name` AS `package`
                    FROM `businesses`
                      JOIN `plans` ON `businesses`.`plan_id` = `plans`.`id`
                    WHERE `user_id`=".$userID;
            $blist = $this->Business->query($sql);

            $profile = $this->Business->find(array('`Business`.`user_id`' => $userID));

            $states = $this->State->myGenerateList(null, 'State.name ASC', null,'{n}.State.name', '{n}.State.name', ' ');

            self::set('plan', $this->obAuth->getPlanName());
            self::set('blist', $blist);
            self::set('states', $states);

            if ($profile) {
                $sql = "SELECT `id`, `detail_type`, `business_id`, `offers`, `description`, `active` FROM `business_details` WHERE `business_id`=".$profile['Business']['id'];
                $bdetails = $this->BusinessDetail->query($sql);

                self::set('profile', $profile);
                self::set('bdetails', $bdetails);
                self::set('plan_id', $profile['Business']['plan_id']);

                if (!empty($this->data['business'])) {
                    if (!$this->data['business']['keyword']) {
                        $pos = (strpos($this->data['account']['keyword'], ","));
                        if ($pos === false) {
                            self::set('alert', 'Invalid keyword format');
                            self::redirect('/admin/bprofile/');
                        }
                        $key = explode(",", $this->data['business']['keyword']);
                        if (count($key) <= 10) {
                            self::set('alert', 'Keyword should not exceed more than 10');
                            self::redirect('/admin/bprofile');
                        }
                    }

                    if ($this->obAuth->getPlanName() == "Premium Listing") {
                        // upload the file
                        // use these to configure the upload path, web path, and overwrite settings if necessary
                        $image_path = $this->Image->upload_image_and_thumbnail($this->data['register'],"name1",573,80,"logo",true);
                        $this->data['business']['logo'] = $image_path;

                        if ($this->Business->_save($this->data['marker']['id'], $this->data['business'])) {
                            self::set('alert', null);
                            self::redirect('/admin/home');
                        } else {
                            self::set('alert', 'Error in updating business information');
                            self::render('bprofile');
                        }
                    } else {
                        $this->Business->_save($this->data['marker']['id'], $this->data['business']);
                        self::set('alert', null);
                        self::redirect('/admin/home');
                    }
                }

                $flag = (isset($this->params['pass'][0])) ? $this->params['pass'][0] : null;
                $key = (isset($this->params['pass'][1])) ? $this->params['pass'][1] : null;

                if ($flag) {
                    switch ($flag) {
                        case "get":
                            $details = $this->BusinessDetail->find('`BusinessDetail`.`id`='.$key);
                            self::set('details', $details);
                        break;

                        case "remove":
                            $this->BusinessDetail->query("UPDATE `business_details` SET `active`=0 WHERE `id`=$key");
                            self::redirect('/admin/bprofile');
                        break;
                    }
                }
            } else {
                self::set('profile', null);
            }
        } else {
            self::set('plan', $this->obAuth->getPlanName());
            self::set('blist', null);
            self::set('state', $state);

            self::set('profile', null);
            self::set('bdetails', null);
            self::set('plan_id', null);

            self::set('details', null);
            self::set('alert', null);
        }



        self::set(array('logo' => $this->Session->read('logo'),
                        'wbtitle' => $this->Session->read('wbtitle')
                        )
                  );
    }

    public function detail()
    {
        # The parameter of lock() is the access level a
        # transporter would have.
        $this->obAuth->lock(array(1));

        $states = $this->State->myGenerateList(null, 'State.name ASC', null,'{n}.State.name', '{n}.State.name', ' ');
        self::set('states', $states);

        $bid = (isset($this->params['pass'][0])) ? $this->params['pass'][0] : $this->data['marker']['id'];
        $sql = "SELECT `businesses`.*,
                       `accounts`.*,
                       `users`.*,
                       `plans`.*
                FROM `businesses`
                  LEFT JOIN `users` ON `businesses`.`user_id`=`users`.`id`
                  LEFT JOIN `accounts` ON `users`.`id`=`accounts`.`user_id`
                  LEFT JOIN `plans` ON `accounts`.`plan_id` = `plans`.`id`
                WHERE `businesses`.`id`=$bid";
        $info = $this->Business->query($sql);

        self::set('info', $info);
        self::set('plan', $info[0]['plans']['name']);

        switch ($this->data['window']['flag']) {
            case "update":
                $bid = $this->data['marker']['id'];
                $uid = $this->data['marker']['user_id'];
                $sw = 0;

                if ($bid && $uid) {
                    switch ($this->data['marker']['plan']) {
                        case "Premium Listing":
                            // upload the file
                            // use these to configure the upload path, web path, and overwrite settings if necessary
                            $image_path = $this->Image->upload_image_and_thumbnail($this->data['register'],"name1",573,80,"logo",true);


                            $data = array('user_id' => $uid,
                                          'name' => $this->data['business']['name'],
                                          'description' => $this->data['business']['description'],
                                          'keyword' => $this->data['business']['keyword'],
                                          'website' => $this->data['business']['website'],
                                          'street' => $this->data['business']['street'],
                                          'city' => $this->data['business']['city'],
                                          'state' => $this->data['state'],
                                          'zip_code' => $this->data['business']['zip_code'],
                                          'contact_no' => $this->data['business']['contact_no'],
                                          'contact_person' => $this->data['business']['contact_person'],
                                          'logo' => $image_path,
                                          'active' => 1
                                         );
                             break;

                         case "Enhanced Listing":
                             $data = array('user_id' => $uid,
                                           'name' => $this->data['business']['name'],
                                           'description' => $this->data['business']['description'],
                                           'keyword' => $this->data['business']['keyword'],
                                           'website' => $this->data['business']['website'],
                                           'street' => $this->data['business']['street'],
                                           'city' => $this->data['business']['city'],
                                           'state' => $this->data['state'],
                                           'zip_code' => $this->data['business']['zip_code'],
                                           'contact_no' => $this->data['business']['contact_no'],
                                           'contact_person' => $this->data['business']['contact_person'],
                                           'active' => 1
                                          );
                             break;

                         case "Basic Listing":
                             $data = array('user_id' => $uid,
                                           'name' => $this->data['business']['name'],
                                           'keyword' => $this->data['business']['keyword'],
                                           'street' => $this->data['business']['street'],
                                           'city' => $this->data['business']['city'],
                                           'state' => $this->data['state'],
                                           'zip_code' => $this->data['business']['zip_code'],
                                           'contact_no' => $this->data['business']['contact_no'],
                                           'contact_person' => $this->data['business']['contact_person'],
                                           'active' => 1
                                          );
                            break;
                        default:
                            $data = null;
                            break;
                    }

                    if (isset($this->data['users'])) $this->User->_save($uid, $this->data['users']); $sw++;
                    if (isset($this->data['business'])) $this->Business->_save($bid, $data); $sw++;

                    if ($sw == 0) {
                        self::set('alert', 'Error updating user profile');
                    } else {
                        $this->set('alert', 'You have successfully updated user profile');
                        self::redirect('/admin/view/');
                    }
                }

                break;
            case "back":
                self::redirect('/admin/view');
                break;
        }

        self::set(array('logo' => $this->Session->read('logo'),
                        'wbtitle' => $this->Session->read('wbtitle'),
                        'deny' => 'You are not authorized to access this page.'
                        )
                  );
    }

    public function deny()
    {
        self::set(array('logo' => $this->Session->read('logo'),
                        'wbtitle' => $this->Session->read('wbtitle'),
                        'deny' => 'You are not authorized to access this page.'
                        )
                  );
    }

    public function add_custom_field()
    {
        $alert = null;
        if ($this->data['field']) {

            $data['field_name'] = $this->data['field']['field_name'];
            $data['field_type'] = $this->data['field_type'];
            $data['field_length'] = $this->data['field']['field_length'];
            $data['active'] = 1;

            $match = $this->Field->find('first', array('conditions' => array('field_name' => $data['field_name'])));
            if ($match) {
                $alert = "Field name already exists";
            } else {
                $id = $this->Field->_save(0, $data);
                if ($id) {
                    $alert = "You have successfully added new custom field";
                } else {
                    $alert = "Error in adding custom field";
                }
            }

        }


        $data_type = array('date' => 'Date', 'varchar' => 'String', 'int' => 'Number');
        self::set('logo', $this->Session->read('logo'));
        self::set('wbtitle', $this->Session->read('wbtitle'));
        self::set('alert', $alert);
        self::set('data_type', $data_type);
    }

    public function assign_custom_fields()
    {
        self::set('logo', $this->Session->read('logo'));
        self::set('wbtitle', $this->Session->read('wbtitle'));
        self::set('alert', null);
    }

    public function manage_offers()
    {
        switch ($this->data['flag']) {
            case "add":
                self::redirect('/admin/add_offers');
                break;

            case "delete":
                if ($this->data['row']['id']) {
                    $data = array('active' => 0);
                    foreach($this->data['row']['id'] as $v) {
                        $this->Offer->id = $v;
                        $this->Offer->save($data);
                    }
                }
                break;

        }

        if ($this->data['search']['value']) {
            $offers = $this->Offer->find('all', array('conditions' => array('offer_name LIKE' => '%'.$this->data['search']['value'].'%')));
        } else {
            $offers = $this->paginate('Offer');
        }

        if ($offers) {
            foreach($offers as $k => $v){
                if (is_numeric($v['Offer']['category'])) {
                    $catname = $this->OfferCategory->get_catname($offers[0]['Offer']['category']);
                    $offers[$k]['Offer']['category'] = $catname['OfferCategory']['offer_category'];
                }
            }
        }

        self::set('offers', $offers);
        self::set('offerCount', count($offers));
        self::set('logo', $this->Session->read('logo'));
        self::set('wbtitle', $this->Session->read('wbtitle'));
        self::set('alert', null);
    }

    public function add_offers($oId = "")
    {
        # The parameter of lock() is the access level a
        # transporter would have.
        $this->obAuth->lock(array(1));

		$alert = null;
        $networks = $this->Network->myGenerateList("Network.active=1", 'Network.network_name ASC', null,'{n}.Network.network_name', '{n}.Network.network_name', ' ');
        $ocategory = $this->OfferCategory->myGenerateList("sub_category=0 and active=1", 'OfferCategory.offer_category ASC', null,'{n}.OfferCategory.id', '{n}.OfferCategory.offer_category', ' ');
        $toscategory = $this->OfferCategory->find('all', array('conditions' => array('sub_category' => 1, 'active' => 1), 'fields' => array('id', 'parent_id', 'offer_category')));
        foreach($toscategory as $v){
            $oscategory[] = $v['OfferCategory'];
        }


        $countries = $this->Country->myGenerateList(null, 'Country.name ASC', null,'{n}.Country.name', '{n}.Country.name', ' ');
        $method = array('POST' => 'POST', 'GET' => 'GET');
        $offer_type = array('B2B', 'B2C', 'Both');
        $fftype = array(
        	'text' => 'Text',
        	'hidden' => 'Hidden',
        	'select' => 'Select',
        	'checkbox' => 'Check box',
        	'phone' => 'Phone Number',
        	'birthday' => 'Birthday',
        	'createdate' => 'Create Date',
        	'ipaddress' => 'I.P. Address',
        	'salutation' => 'Salutation'
        );
        $validation = array(
        	'email' => 'Email',
			'url' => 'URL',
			'date' => 'Date',
			'digits' => 'Digits',
			'number' => 'Number (with decimal number)',
			'maxlength' => 'Maximum Length',
			'minlength' => 'Minimum Length',
			'phoneUS' => 'Valid US phone number'
		);
		$image_sizes = array (
			'468x60' => '(468x60) Full Banner',
			'234x60' => '(234x60) Half Banner',
			'88x31' => '(88x31) Micro Banner',
			'120x90' => '(120x90) Button 1',
			'120x60' => '(120x60) Button 2',
			'120x240' => '(120x60) Vertical Banner',
			'125x125' => '(125x125) Square Button',
			'728x90' => '(728x90) Leader board',
		);

        // check field form update and delete
        if ($this->params['pass']) {
            if (isset($this->params['pass'][1]) && isset($this->params['pass'][3])) {
                switch($this->params['pass'][2]){

                    case "delete":
                        $this->Field->id = $this->params['pass'][3];
                        $this->Field->save(array('active' => 0));
                        break;

                } // switch

                $_field = $this->Field->find('first', array('conditions' => array('id' => $this->params['pass'][3])));

                self::set('_fieldd', $_field);
                self::set('edit_field_id', $this->params['pass'][3]);

            } else {
                self::set('_fieldd', null);
                self::set('edit_field_id', 0);
            }
        } else {
            self::set('_fieldd', null);
            self::set('edit_field_id', 0);
        }

        // get offer details if edit
        if ($oId) {
            $offers = $this->Offer->find('first', array('conditions' => array('id' => $oId)));
            $ffields = $this->Field->find('all', array('conditions' => array('offerId' => $oId, 'active' => 1)));
            $fform = $this->Field->find('first', array('conditions' => array('offerId' => $oId), 'fields' => array('form_name', 'form_action')));

            self::set('offerId', $oId);
            self::set('offers', $offers);
            self::set('fields', $ffields);
            self::set('fform', $fform);
            self::set('page_title', "View | Edit Offer");
        } else {
            self::set('offerId', null);
            self::set('offers', null);
            self::set('fields', null);
            self::set('fform', null);
            self::set('page_title', "New Offer");
        }

		if ($this->data['window']['flag']) {
			switch ($this->data['window']['flag']) {
				case "cancel" && "offer":
					self::redirect("/admin/manage_offers");
					break;
			}
		}


        //if ($oId) {
        //} else {
            if ($this->data['ad_network'] && $this->data['offer']['offer_name'] && $this->data['post_method'] &&
                $this->data['offer']['offer_copy'] && $this->data['category'] && $this->data['offer']['keywords']
                ) {

                if ($this->data['offer']['manage'] == "manage") {
                    self::redirect('/admin/manage_offers');
                }

                // upload image
                $image_path_1 = "";
                $image_path_2 = "";
                if ($this->data['offer']['creative_1']) {
                    $image1['Image'] = $this->data['offer']['creative_1'];
                    $size1 = self::set_image_size('creative1_size');
                    $image_path_1 = $this->Image->upload_image_and_thumbnail($image1,"creative_1",$size1[0],$size1[1],$size1[0], $size1[0],"logo",false);
                }

                if ($this->data['offer']['creative_2']) {
                    $image2['Image'] = $this->data['offer']['creative_2'];
                    $size2 = self::set_image_size('creative2_size');
                    $image_path_2 = $this->Image->upload_image_and_thumbnail($image2,"creative_2",$size2[0],$size2[1],$size2[0], $size2[0],"logo",false);
                }

                // prepare offer data
                $offer_data['ad_network'] = $this->data['ad_network'];
                $offer_data['offer_name'] = $this->data['offer']['offer_name'];
                $offer_data['offer_url'] = $this->data['offer']['offer_url'];
                $offer_data['post_method'] = $this->data['post_method'];
                $offer_data['offer_copy'] = $this->data['offer']['offer_copy'];
                $offer_data['category'] = $this->data['category'];
                $offer_data['sub_category'] = isset($this->data['sub_category'])?$this->data['sub_category']:null;
                $offer_data['keywords'] = $this->data['offer']['keywords'];
                $offer_data['target_country'] = $this->data['target_country'];
                $offer_data['offer_type'] = $this->data['offer_type'];
                $offer_data['coupon_code'] = $this->data['offer']['coupon_code'];
                $offer_data['date_added'] = date('Y-m-d H:i:s');
                $offer_data['date_started'] = date('Y-m-d', strtotime(str_replace("-", "/", $this->data['offer']['date_started'])));
                $offer_data['date_ended'] = date('Y-m-d', strtotime(str_replace("-", "/", $this->data['offer']['date_ended'])));
                $offer_data['creative_1'] = $image_path_1;
                $offer_data['creative_2'] = $image_path_2;
                $offer_data['active'] = 1;

                // save data
                $new_offer_id_val = ($oId)?$oId:0;
                $new_offer = $this->Offer->_save($new_offer_id_val, $offer_data);

                // prepare custom field data
                $custom_data['offerId'] = $new_offer;
                $custom_data['form_name'] = $this->data['custom']['form_name'];
                $custom_data['form_action'] = $this->data['custom']['form_action'];

                $new_custom_field_id_val = isset($this->data['field']['edit_field_id'])?$this->data['field']['edit_field_id']:0;
                $new_custom_field_id = $this->Field->_save($new_custom_field_id_val, $custom_data);
                if ($new_custom_field_id) {
                    $custom_data = array();
                    $custom_keys = array_keys($this->data['custom']);

                    foreach($custom_keys as $i => $v){
                        $marker = "";
                        $pos = stripos($v, "field_type-");
                        if ($pos === false) {
                        } else {
                            $field = explode("field_type-", $v);
                            $marker = $field[1];
                        }

    					if ($marker) {
                            if (isset($this->data['custom'])) {
                                if ($this->data['custom']['field_delete-'.$marker] == 0) {
                                    $custom_data[$i]['offerId'] = $new_offer;
                                    $custom_data[$i]['field_name'] = $this->data['custom']['field_name-'.$marker];
                                    $custom_data[$i]['field_label'] = $this->data['custom']['field_label-'.$marker];
                                    $custom_data[$i]['field_type'] = $this->data['custom']['field_type-'.$marker];

                                    if (is_array($this->data['custom']['field_value-'.$marker])) {
                                    	$value = $this->data['custom']['field_value-'.$marker][0];
                                    } else {
                                    	$value = $this->data['custom']['field_value-'.$marker];
                                    }

                                    $custom_data[$i]['field_value'] = htmlentities($value, ENT_QUOTES);

                                    if (isset($this->data['custom']['field_validation-'.$marker])) {
                                        $custom_data[$i]['validation'] = $this->data['custom']['field_validation-'.$marker];
                                        if ($this->data['custom']['field_validation-'.$marker] == 'maxlength' ||
                                            $this->data['custom']['field_validation-'.$marker] == 'minlength') {

                                        	if (isset($this->data['custom']['mlength'])) {
                                        	    $custom_data[$i]['validation_param'] = $this->data['custom']['mlength'];
                                        	} else {
                                        	    $custom_data[$i]['validation_param'] = 5;
                                            }

                                        }
                                    }

                                    $custom_data[$i]['required'] = $this->data['custom']['field_required-'.$marker];
                                    $custom_data[$i]['active'] = 1;

                                    if ($custom_data[$i]['field_type'] == 'createdate') {
                                    	$custom_data[$i]['extras'] = isset($this->data['dateformat'])?$this->data['dateformat']:null;
                                    } else if ($custom_data[$i]['field_type'] == 'checkbox') {
                                    	$custom_data[$i]['extras'] = isset($this->data['custom']['labelpos'])?$this->data['custom']['labelpos']:null;
                                    //} else if ($custom_data[$i]['field_type'] == 'text') {
                                    } else {
                                    	$custom_data[$i]['extras'] = null;
                                    }
                                }
                            }
    					}

                    }

                    // save data
                    if ($custom_data) {
                        foreach($custom_data as $v) {
                            $new_field[] = $this->Field->_save(0, $v);
                        }

    					if ($new_field) {
    						$alert = "You have successfully added new offer";
    					} else {
    						$alert = "Error on saving offer details";
    					}
    				}
                }

            }
        //}

        self::set('network', $networks);
        self::set('ocategory', $ocategory);
        self::set('oscategory', json_encode($oscategory));
        self::set('post_method', $method);
        self::set('offer_type', $offer_type);
        self::set('countries', $countries);
        self::set('validation', $validation);
        self::set('image_sizes', $image_sizes);
        self::set('fftype', $fftype);
        self::set('fftype', $fftype);
        self::set('logo', $this->Session->read('logo'));
        self::set('wbtitle', $this->Session->read('wbtitle'));
        self::set('alert', $alert);
    }

    public function export_form_fields($offerId)
    {
        $this->layout = "";
        $fields = $this->Field->find('all', array('conditions' => array('offerId' => $offerId)));
        $method = $this->Offer->find('first', array('conditions' => array('id' => $offerId)));

        $output = "<script type='text/javascript' src='http://".$_SERVER['HTTP_HOST']."/lds/js/jquery.js'></script>\r\n";
        $output .= "<script type='text/javascript' src='http://".$_SERVER['HTTP_HOST']."/lds/js/jquery_plugins/jquery.metadata.js'></script>\r\n";
        $output .= "<script type='text/javascript' src='http://".$_SERVER['HTTP_HOST']."/lds/js/jquery_plugins/jquery.validate.js'></script>\r\n";
        $output .= "<script type='text/javascript' src='http://".$_SERVER['HTTP_HOST']."/lds/js/cmxforms.js'></script>\r\n";
        $output .= "<link rel='stylesheet' type='text/css' href='http://".$_SERVER['HTTP_HOST']."/lds/css/cmxform.css' />\r\n";

        $output .= "<script type='text/javascript'>\r\n
                    $().ready(function() {\r\n
                        $('#".$fields[0]['Field']['form_name']."').validate({\r\n
                            errorLabelContainer: $('#".$fields[0]['Field']['form_name']." div.error')\r\n
                        });\r\n
                    });\r\n
                    \r\n
                    function getsysdatetime()\r\n
                    {\r\n
                        var mydate = new Date();\r\n
                        var timestamp = mydate.getFullYear() + '-' + (mydate.getMonth() + 1) + '-' + mydate.getDate() + ' ' + mydate.getHours() + ':' + mydate.getMinutes() + ':' + mydate.getSeconds();\r\n
                        return timestamp;\r\n
                    }\r\n
                    </script>\r\n";

        $output .= "<style type='text/css'>\r\n
                        .".$fields[0]['Field']['form_name']." fieldset p.error label { color: red; }\r\n
                        form.".$fields[0]['Field']['form_name']." label.error {\r\n
                            display: block;\r\n
                            margin-left: 1em;\r\n
                            width: auto;\r\n
                        }\r\n
                        div.error {\r\n
                            background-color: #eee;\r\n
                            border: 1px solid red;\r\n
                            margin: 5px;\r\n
                            padding: 5px;\r\n
                        }\r\n
                    </style>\r\n";

        $output .= "<form id='".$fields[0]['Field']['form_name']."' name='".$fields[0]['Field']['form_name']."' action='".$fields[0]['Field']['form_action']."' method='".$method['Offer']['post_method']."' class='".$fields[0]['Field']['form_name']."'>\r\n";
        $output .= "<table width='100%'>\r\n";
        $output .= "<tr>\r\n";
        $output .= "<td colspan='2'><div class='error'></div></td>\r\n";
        $output .= "</tr>\r\n";

        foreach($fields as $k => $v) {
            $class = "";
            $output .="<tr>\r\n";
            $output .= "<td width='20%' align='right'>".$v['Field']['field_label']."&nbsp;&nbsp;</td>\r\n";
            $output .= "<td>\r\n";

            if ($v['Field']['field_type']) {
                // add jquery validation
                if ($v['Field']['validation']) {
                    $pos = stripos($v['Field']['validation'], "length");
                    if ($pos === false) {
                        $class = $v['Field']['validation'].":true";
                    } else {
                        $class = $v['Field']['validation'].":".$v['Field']['validation_param'];
                    }
                }

                // check if field is required, if yes, add it to validation
                if ($v['Field']['required'] == 1) {
                    if ($class) {
                        $class = "{required:true,".$class."}";
                    } else {
                        $class = "{required:true}";
                    }

                }

                $title = ($v['Field']['validation'])?$v['Field']['validation']:$v['Field']['field_name'];

                switch($v['Field']['field_type']){

                    case "select":
                        $options = explode(";", html_entity_decode($v['Field']['field_value']));
                        $output .= "<select id='".$v['Field']['field_name'].$k."' name='".$v['Field']['field_name']."' class='{$class}' title='Enter valid ".$title."'>\r\n";
                        foreach($options as $opt){
                            //$output .= "<option value='".$opt."'>".$opt."</option>\r\n";
                            if (stripos($opt, '=>') === false) {
                                $output .= "<option value={$opt}>{$opt}</option>";
                            } else {
                                $key = explode("=>", $opt);
                                $output .= "<option value=".$key[0].">".$key[1]."</option>";
                            }
                        }

                        $output .= "</select>\r\n";
                        break;

                    case "checkbox":
                        if ($v['Field']['extras']) {

                            switch($v['Field']['extras']){
                                case "left":
                                    $output .= "";
                                    break;

                                case "right":
                                    break;
                            } // switch

                        }
                        break;

                    case "createdate":
                        if ($v['Field']['extras']) {
                            $output .= "<input type='hidden' id='".$v['Field']['field_name'].$k."' name='".$v['Field']['field_name']."' value='".date('Y-m-d H:i:s')."'>\n\r";
                        } else {
                            $output .= "<input type='hidden' id='".$v['Field']['field_name'].$k."' name='".$v['Field']['field_name']."' value='".date('m-d-Y H:i:s')."'>\n\r";
                        }                      
                        //$output .= "<script type='text/javascript'>\n\r";
                        //$output .= "document.getElementById('".$v['Field']['field_name'].$k."').value = getsysdatetime();\n\r";
                        //$output .= "</script>\n\r";
                        break;

                    case "ipaddress":
                        $output .= "<input type='hidden' id='".$v['Field']['field_name'].$k."' name='".$v['Field']['field_name']."' value='".$_SERVER['REMOTE_ADDR']."'>\n\r";
                        break;

                    default:
                        $output .= "<input type='".$v['Field']['field_type']."' id='".$v['Field']['field_name'].$k."' name='".$v['Field']['field_name']."' title='Enter valid ".$title."' value='".$v['Field']['field_value']."' class='{$class}' />\r\n";
                        break;

                } // switch
            }

            $output .="</td>\r\n";
            $output .="</tr>\r\n";
        }

        $output .= "<tr>\r\n";
        $output .= "<td>&nbsp;</td>\r\n";
        $output .= "<td><input type='submit' value='Save'></td>\r\n";
        $output .= "</tr>\r\n";

        $output .= "</table>\r\n";
        $output .= "</form>\r\n";


        self::set('output', $output);
        self::set('source', htmlentities($output, ENT_QUOTES));

    }

    public function manage_category()
    {
        switch ($this->data['flag']) {
            case "add":
                self::redirect('/admin/add_category');
                break;

            case "delete":
                if ($this->data['row']['id']) {
                    $data = array('active' => 0);
                    foreach($this->data['row']['id'] as $v) {
                        $this->OfferCategory->id = $v;
                        $this->OfferCategory->save($data);
                    }
                }
                break;

        }

        if ($this->data['search']['value']) {
            $offer_category = $this->OfferCategory->find('all', array('conditions' => array('offer_category LIKE' => '%'.$this->data['search']['value'].'%'), 'order' => 'sub_category DESC'));
        } else {
            $offer_category = $this->paginate('OfferCategory');
        }

        self::set('logo', $this->Session->read('logo'));
        self::set('wbtitle', $this->Session->read('wbtitle'));
        self::set('alert', null);
        self::set('categories', $offer_category);
        self::set('categoryCount', count($offer_category));
    }

    public function add_category()
    {
        $alert = null;
        $pcat = $this->OfferCategory->myGenerateList('sub_category = 0 and active=1', 'offer_category asc', null, '{n}.OfferCategory.id', '{n}.OfferCategory.offer_category');
        if ($this->data['category']['offer_category']) {
            $data['offer_category'] = $this->data['category']['offer_category'];
            $data['active'] = 1;
            switch($this->data['ctype']){
                case "category":
                    $data['sub_category'] = ($this->data['ctype'] == 1)?1:0;
                    break;

                case "sub-category":
                    $data['sub_category'] = ($this->data['ctype'] == 0)?1:0;
                    $data['parent_id'] = $this->data['pcategory'];
                    break;
            } // switch

            $catId = $this->OfferCategory->_save(0, $data);
            if ($catId) {
                $alert = "You have successfully added new category";
            }
        }

        switch($this->data['window']['flag']){
            case "category":
                self::redirect("/admin/manage_category");
                break;
        } // switch

        self::set('pcat', $pcat);
        self::set('logo', $this->Session->read('logo'));
        self::set('wbtitle', $this->Session->read('wbtitle'));
        self::set('alert', $alert);
        self::set('categoryId', isset($categoryId)?$categoryId:null);
        self::set('ctype', array('category' => 'category', 'sub-category' => 'sub-category'));
    }

    public function manage_network()
    {
        switch ($this->data['flag']) {
            case "add":
                self::redirect('/admin/add_network');
                break;

            case "delete":
                if ($this->data['row']['id']) {
                    $data = array('active' => 0);
                    foreach($this->data['row']['id'] as $v) {
                        $this->Network->id = $v;
                        $this->Network->save($data);
                    }
                }
                break;

        }

        if ($this->data['search']['value']) {
            $networks = $this->Network->find('all', array('conditions' => array('network_name LIKE' => '%'.$this->data['search']['value'].'%')));
        } else {
            $networks = $this->paginate('Network');
        }

        self::set('logo', $this->Session->read('logo'));
        self::set('wbtitle', $this->Session->read('wbtitle'));
        self::set('alert', null);
        self::set('networks', $networks);
        self::set('networkCount', count($networks));
    }

    public function add_network()
    {
        $alert = null;
        if ($this->data['network']) {
            if ($this->data['network']['network_name']) {
                $data['network_name'] = addslashes($this->data['network']['network_name']);
                $data['active'] = 1;
                $networkId = $this->Network->_save(0, $data);
                if ($networkId) {
                    $alert = "You have successfully added a network";
                } else {
                    $alert = "Error";
                }
            }
        }

        switch($this->data['window']['flag']){
            case "networks":
                self::redirect("/admin/manage_network");
                break;

        } // switch

        self::set('logo', $this->Session->read('logo'));
        self::set('wbtitle', $this->Session->read('wbtitle'));
        self::set('alert', $alert);
        self::set('networkId', isset($networkId)?$networkId:null);
    }

    public function preview($img)
    {
    	$this->layout = "";

        self::set('logo', $this->Session->read('logo'));
        self::set('wbtitle', $this->Session->read('wbtitle'));
        self::set('img', base64_decode($img));
    }



	/**
	 *
	 * private methods
	 *
	 */
    private function set_image_size($field_name)
    {
		// get image size
		if ($this->data['offer'][$field_name]) {
			$size = explode("x", $this->data['offer'][$field_name]);
		} else {
            $size[0] = 100;
            $size[1] = 100;
		}

		return $size;
    }
}
?>